package com.mango.data.structure.bitmap;

/**
 * 位图
 * @Author: mango
 * @Date: 2022/5/12 10:36 下午
 */
public class Bitmap {
    // 用int数组实现，一个int 4个字节32位
    private int[] data;
    private int size;
    private final int bitSize = 32;

    public Bitmap(int size){
        this.size = size;
        int dataSize = size % bitSize == 0 ? size / bitSize : (size / bitSize) + 1;
        this.data = new int[dataSize];
    }

    private void check(int index){
        if(index >= this.size){
            throw new RuntimeException("index " + index + " out of range size " + this.size);
        }
    }

    /**
     * 设置index的位为1
     * @param index
     */
    public void bitOne(int index){
        this.check(index);
        this.data[index/bitSize] = this.data[index/bitSize] | (1 << (index % bitSize));
    }

    /**
     * 设置index的位为0
     * @param index
     */
    public void bitZero(int index){
        this.check(index);
        this.data[index/bitSize] = this.data[index/bitSize] & (~(1 << (index % bitSize)));
    }

    /**
     * 获取inde位置的值，是0或者1
     * @param index
     */
    public int getBit(int index){
        this.check(index);
        return (this.data[index/bitSize] >> (index % bitSize)) & 1;
    }

}
